'''Functions for conversion of BibTeX data to a list of python dictionaries
and related scripts. [Depreciated]

@status:
    Depreciated. This module has been retained for historical reasons,
    but most, if not all, of its functionality is available using the
    L{Bibliography} class.

@copyright: (c) 2004-2009, Jim Pitman, Dept. Statistics, U.C. Berkeley
    <http://www.stat.berkeley.edu/users/pitman>
@copyright: (c) 2009-2010, Benjamin Kalish

@license:
    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by the Free
    Software Foundation; either version 2 of the License, or (at your option)
    any later version.

    This program is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
    more details.
'''

__docformat__ = 'epytext'

import string
import types

from simpleparse.error import ParserSyntaxError

from bkn.bibtex._bibtex_parser import *

def dict2bibtex(d):
    '''Simple function to return a bibtex entry from a python dictionary
    
    @deprecated:
        The L{Record} class in the L{Bibliography} module should be used
        instead.
    '''
    outstring =  '@' + d.get('TYPE','UNKNOWN') + '{' + d.get('KEY','') + ',\n'
    kill_keys = ['TYPE','KEY','ORDER']
    top_keys = ['AUTHOR','TITLE','YEAR']
    top_items = []
    rest_items = []
    for k in d.keys():
        if k in top_keys:
            top_items = top_items + [ ( k , d[k] )]
        elif not k in kill_keys:
            rest_items = rest_items + [ ( k , d[k] )]
    rest_items.sort()
    for k in top_items + rest_items:
        outstring = outstring + '\t' + k[0] + ' = {' + k[1] + '},\n'
    outstring = outstring +  '}\n\n'
    return outstring
    
def wget(address):
    '''Returns string from httpaddress, or the string 'IOError'
    
    @deprecated:
        This functunality is outside the scope of the bkn.bibtex package.
    '''
    try:
        infile = urllib.urlopen(address)
        instring = infile.read()
        if string.find (instring, '404 Not Found') >= 0:
            return 'IOError'
        elif string.find (instring, 'Error 404') >= 0:
            return 'IOError'
        else: 
            return instring
    except IOError:
        return 'IOError'

def get_bbl(fname):
    '''Convert a typical .bbl file into a dictionary
    
    @deprecated:
        This method would have been used most often to enchance a
        Bibliography with BibTeX output this can now be achieved with
        the Bibliography.add_bibtex_output() method.
    '''
    infile = open(fname + '.bbl','r')
    instring = infile.read()
    instring = instring.split('\\end{thebibliography}')[0]
    items = instring.split('\\bibitem{')
    bbl= {}
    bbl['__top_line__'] = items[0]
    bbl['__key_order__'] = []
    for item in items[1:]:
        k,v = item.split('}',1)
        v = v.strip()
        bbl[k] = v
        bbl['__key_order__'] += [k]
    return bbl 

def make_tex(params):  
    '''Make a small tex file for processing biblio data with input from dictionary params.
    
    @deprecated:
        This functunality is outside the scope of the bkn.bibtex package.
    '''
    tex = '''
\\documentclass{article}
*packages_line*
\\nonstopmode
\\begin{document}
\\nocite{*}
\\renewcommand{\\refname}{*refname*}
\\bibliographystyle{*bibliographystyle*}
\\bibliography{*bibfnames*}
\\end{document}
'''
    for k in params.keys():
        tex = tex.replace('*' + k + '*' , params[k] )
    outfile = open( params['tmpfname'] + '.tex','w')
    outfile.write(tex)
    outfile.close()
    p = 'Wrote file ' + params['tmpfname'] + '.tex\n'
    #p+= 'to process data from these BibTex files:\n'
    #p+= params['bibfnames']
    #p+= '\nwith BibTex style "' + params['bibliographystyle'] + '"\n\n'
    return p

def make_files(fname):
    '''Usual pdflatex/bibtex processing of file fname.tex to create .aux, .bbl, .pdf etc.

    @deprecated:
        This functunality is outside the scope of the bkn.bibtex package.
    '''

    p = ''
    os.popen('pdflatex ' + fname, "r").read()
    p += os.popen('bibtex ' + fname, "r").read()
    os.popen('pdflatex ' + fname, "r").read()
    p += os.popen('pdflatex ' + fname, "r").read()
    return p

def bib2tex(bibfname,outfname,params):
    '''Create a .tex file from a .bib and some parameters.
        @deprecated:
        This functunality is outside the scope of the bkn.bibtex package.
    '''

    params['bibfnames'] = bibfnames
    params['outfname'] =  outfname
    make_tex(params)
    print make_files(outfname)

def make_all_files(params):
    '''Usual pdflatex/bibtex processing of file fname.tex to create .aux, .bbl, .pdf etc.
    
    @deprecated:
        This functunality is outside the scope of the bkn.bibtex package.
    '''

    p = make_tex(params)
    fname = params.get('tmpfname','tmp')
    os.popen('pdflatex ' + fname, "r").read()
    p += os.popen('bibtex ' + fname, "r").read()
    os.popen('pdflatex ' + fname, "r").read()
    p += os.popen('pdflatex ' + fname, "r").read()
    return p

def xmake_bbl(comparison,selection,params):  
    '''???
    @deprecated:
        Use methods in the L{Bibliography} module.
    '''

    bibfname = params['bibfname']
    outfname = params['outfname']
    ### based only on data in bibfname + '.bib'
    ##  create .tex and .bbl files
    bib2tex(bibfname,outfname,params)   
    ### extract the relevant .bbl entries 
    bbl = get_bbl(outfname)
    infile = open(bibfname + '.bib','r')
    bibstring= infile.read()
    dls = read_bibstring(bibstring)
    #for d in dls:
    #   for k in d.keys():
    #       print k, d[k]
    dls = [d for d in dls if selection(d)]
    dls.sort(comparison)
    p = bbl['__top_line__'] 
    for d in dls:
        p += '\\bibitem{' + d['citekey'] + '} '  + bbl[d['citekey']] + '\n\n'
    p += '\\end{thebibliography}\n'
    ### rewrite the extracted/sorted .bbl entries 
    outfile = open( outfname + '.bbl','w')
    outfile.write(p)
    outfile.close()
    return p

def make_bbl(comparison,selection,display,params):  
    '''???
    @deprecated:
        Use methods in the L{Bibliography} module.
    '''
    tmpfname = params['tmpfname']
    ##outfname = params['outfname']
    ### extract the relevant .bbl entries 
    bbl = get_bbl(tmpfname)
    dls = []
    p = ''
    for f in params['bibfnames'].split(','):
        infile = open(f + '.bib','r')
        bibstring= infile.read()
        for d in read_bibstring(bibstring):
            d['bibfile'] = f
            # This check is a quick fix for a bug with @strings commands - BK 3 Jan 2010
            if d.has_key('citekey'):
                d['bibitem'] = bbl.get(d['citekey'],d['citekey'] + ' not found ' )
            if selection(d): dls += [d]
    dls.sort(comparison)
    count = 0
    for d in dls:
        count += 1
        d['count'] = str(count)
        p += display(d)
    ### rewrite the extracted/sorted .bbl entries 
    return p
    
def make_bbl_dict(params):  
    '''???
    @deprecated:
        Use methods in the L{Bibliography} module.
    '''
    tmpfname = params['tmpfname']
    ##outfname = params['outfname']
    ### extract the relevant .bbl entries 
    bbl = get_bbl(tmpfname)
    bbld = {}
    p = ''
    for f in params['bibfnames'].split(','):
        infile = open(f + '.bib','r')
        bibstring= infile.read()
        for d in read_bibstring(bibstring):
            d['bibfile'] = f
            d['bibitem'] = bbl.get(d['citekey'],d['citekey'] + ' not found ' )
            bbld[d['citekey']] = d
    return bbld

#   EXAMPLE
#   params = {}
#   params['packages_line'] = '\\usepackage[utf8]{inputenc}'
#   params['refname'] = 'Publications related to J. F. C. Kingman'
#   params['bibliographystyle'] = 'plain'  
#   params['bibfnames'] = ','.join( [ f.replace('.bib','') for f in glob.glob('./bibfiles/*.bib')])
#   params['tmpfname'] = 'tmp_kingman'
#   params['outfname'] = 'kingman'
#   print make_all_files(params)
#   bbl = make_bbl(comparison,selection,display,params)
#   print bbl
#   os.popen('pdflatex ' + fname, "r").read()
#   print os.popen('pdflatex ' + fname, "r").read()
